// 订单模块
// 购物车
const sequelize = require('../config/operateDB');
const {Sequelize, DataTypes, Op} = require('sequelize');
const { Products } = require('./product');
const {ShopCar} = require('./shopCar');
const session = require('koa-session');

const Order = sequelize.define('order', {
    id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
    },
    // orderId: {
    //     type: DataTypes.BIGINT,
    //     allowNull: false,
    // },
    price: {
        type: DataTypes.FLOAT,
        allowNull: false,
    },
    contactUser: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    contactTel: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    userId: {
        type: DataTypes.UUID,
        allowNull: false,
    }
}, {

});

const OrderDetails = sequelize.define('orderDetails', {
    id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
    },
    // 商品名称
    name: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    productId: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    orderId: {
        type: DataTypes.BIGINT,
        allowNull: false,
    },
    number: {
        type: DataTypes.BIGINT,
        allowNull: false,
    },
    // 商品图片
    imgSrc: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    // 商品介绍
    detail: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    // 店铺
    owner: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    // 分类id
    catagoryId: {
        type: DataTypes.BIGINT,
        allowNull: true,
    },
    // 分类名称
    catagoryName: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    // 价格
    price: {
        type: DataTypes.FLOAT,
        allowNull: false,
    },
}, {

});

Order.sync();
OrderDetails.sync();


const orderModel = {
    async getOrder(ctx) {
        const params = ctx.query;
        // const count = await Order.count();
        const {offset = 0, limit = 10, contactUser} = params;
        const userId = ctx.session.sessionData.isManager ? undefined : ctx.session.sessionData.id;
        const queryRequest = {
            where: userId ? {
                userId: userId,
            } : {
                contactUser: {
                    [Op.like]: '%' + contactUser + '%'
                }
            },
            limit: parseInt(limit),
            offset: parseInt(offset),
            raw: true,
        }
        const { count, rows } = await Order.findAndCountAll(queryRequest);
        if (0 !== count) {
            for (let i = 0; i <= rows.length - 1; i++) {
                const orderDetails = await OrderDetails.findAll({
                    where: {
                        orderId: rows[i].id,
                    },
                    raw: true,
                });

                rows[i].orderDetails = orderDetails;
            }
            
        }
        ctx.pageRes({
            limit,
            offset,
            list: rows,
            total: count,
        });
    },

    async addOrder(ctx) {
        
        const params = ctx.request.body;

        const validFlag = this.validOrder(ctx, params);
        if (validFlag) {
            // 如果是购物车购买
            if (params.isCarSale) {
                const t = await sequelize.transaction();
                try {
                    const orderInfo = await Order.create({
                        price: params.price,
                        contactUser: ctx.session.sessionData.name,
                        contactTel: ctx.session.sessionData.telNo,
                        userId: ctx.session.sessionData.id,
                    }, { transaction: t });
                    const shopCarId = params.products.map(product => {
                        return product.id;
                    })
                    ShopCar.destroy({
                        where: {
                            id: {[Op.in]: shopCarId},
                        }
                    }, { transaction: t })
                    const orderDetail = params.products.map(product => {
                        return {
                            productId: product.productId,
                            name: product.name,
                            imgSrc: product.imgSrc,
                            detail: product.detail,
                            owner: product.owner,
                            number: product.number,
                            catagoryId: product.catagoryId,
                            catagoryName: product.catagoryName,
                            price: product.price,
                            orderId: orderInfo.dataValues.id,
                        }
                    })
                    await OrderDetails.bulkCreate(orderDetail, { transaction: t });
                    await t.commit();
                    ctx.success('订单添加成功!');
                } catch(err) {
                    await t.rollback();
                    ctx.serviceError('程序出错', err.toString());
                }
            } else {
                const t = await sequelize.transaction();
                try {
                    const orderInfo = await Order.create({
                        price: params.price,
                        contactUser: ctx.session.sessionData.name,
                        contactTel: ctx.session.sessionData.telNo,
                        userId: ctx.session.sessionData.id,
                    }, { transaction: t });
                    console.log(orderInfo);
                    const orderDetail = params.products.map(product => {
                        return {
                            productId: product.id,
                            name: product.name,
                            imgSrc: product.imgSrc,
                            detail: product.detail,
                            owner: product.owner,
                            number: product.number,
                            catagoryId: product.catagoryId,
                            catagoryName: product.catagoryName,
                            price: product.price,
                            orderId: orderInfo.dataValues.id,
                        }
                    }, { transaction: t })
                    await OrderDetails.bulkCreate(orderDetail);
                    await t.commit();
                    ctx.success('订单添加成功!');
                } catch(err) {
                    await t.rollback();
                    ctx.serviceError('程序出错', err.toString());
                }
            }

            
        }
    },
    validOrder(ctx, params) {
        if (!params.price) {
            ctx.errorParams('商品价格不存在！');
            return false;
        }
        // else if (!params.contactUser) {
        //     ctx.errorParams('联系人不存在！');
        //     return false;
        // } else if (!params.contactTel) {
        //     ctx.errorParams('联系电话不存在！');
        //     return false;
        // } 
        else if (0 === params.products.length) {
            ctx.errorParams('商品不存在！');
            return false;
        } else {
            let flag = true;
            params.products.some(product => {
                if (!product.number) {
                    flag = false;
                    ctx.errorParams('商品的数量不存在！');
                    return true;
                } else {
                    return false;
                }
            });
            return flag;
        }
    },
    validCar(ctx, params) {
        if (!params.id) {
            ctx.errorParams('id不存在！');
            return false;
        } else if (!params.number) {
            ctx.errorParams('商品数量不存在！');
            return false;
        } else {
            return true;
        }
    },
    async deleteOrder(ctx)  {
        const deleteId = ctx.request.body.id;
        if (!deleteId) {
            ctx.errorParams('id不存在！');
        } else {
            const t = await sequelize.transaction();
            try {
                await Order.destroy({
                    where: {
                        id: deleteId,
                    }
                }, {transaction: t});
                await OrderDetails.destroy({
                    where: {
                        orderId: deleteId
                    }
                }, {transaction: t})
                await t.commit();
                ctx.success('删除成功！', {
                    id: deleteId,
                })
            } catch (err) {
                await t.rollback();
                ctx.serviceError('程序出错', err.toString());
            }
            
        }
        
    },
};


module.exports = {
    orderModel,
    Order
};